﻿using DAL.Gonggong;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class KangDAL
    {
        /// <summary>
        /// 依赖注入
        /// </summary>
        private readonly MyDbContext db;

        public KangDAL(MyDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 康复新增
        /// </summary>
        /// <param name="info">康复类</param>
        /// <returns></returns>
        public int Add(Kang info)
        {
            try
            {
                db.Kang.Add(info);
                info.Bianhao = DateTime.Now.ToString("yyyyMMdd-0HH");
                return db.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 显示+查询+分页
        /// </summary>
        /// <param name="name">食谱标题</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页多少条</param>
        /// <returns></returns>
        public Fenye<Kang> Show(string ?name,int pageindex=1,int pagesize = 2)
        {
            try
            {
                Fenye<Kang> fenye = new Fenye<Kang>();

                var list = db.Kang.AsQueryable().Where(x=>x.Delete==0);
                if(list != null)
                {
                    if (!string.IsNullOrEmpty(name))
                    {
                        list=list.Where(x => x.Name.Contains(name));
                    }
                }
                fenye.ZongHang = list.Count();
                fenye.ZongYe = Convert.ToInt32(Math.Ceiling(list.Count()*1.0/pagesize));
                fenye.ZongShu = list.OrderBy(x=>x.Id)
                    .Skip((pageindex-1)*pagesize)
                    .Take(pagesize)
                    .ToList();
                return fenye;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public int Delete(int id)
        {
            try
            {
                var res = db.Kang.Find(id);
                res.Delete = 1;
                return db.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public int UpdByState(int id)
        {
            try
            {
                var res = db.Kang.Find(id);
                res.State = !res.State;
                return db.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
